﻿using System;
using Gfw.Infrastructure.ExceptionImpl;
using Gfw.Infrastructure.Facilities;
using Gfw.Infrastructure.Stock.Facilities;
using Gfw.Repositories.Stock;
using Gfw.Repository;

namespace Gfw.BLL.Basic.Stock.Facilities
{
    public class AutoBuyFacility : IFacility
    {
        private string _userId;

        public AutoBuyFacility(string userId)
        {
            _userId = userId;
        }

        public void Execute(Repository.UnitOfWork unitOfWork = null)
        {
            if (unitOfWork != null)
                throw new GfwException("这里是强制性买入股票，应该具备异步执行，不论成败。");

            UserAccountRepository accountRep = new UserAccountRepository();
            var account = accountRep.Get(_userId);
            if (account.StockMoney >= 200)
            {
                if (StockManager.ServcieIsRunning())
                {
                    var price = StockManager.CurrentPrice;
                    decimal maxBuy = Math.Floor(account.StockMoney/price);
                    if (maxBuy >= 100)
                    {
                        //满足自动买入条件，自动买入股票
                        BuyTradeFacility bf = new BuyTradeFacilityImpl(_userId, maxBuy, price, Gfw.Infrastructure.Stock.Enums.ForceTradeTypeEnum.ForceBuy);
                        bf.Execute();
                    }
                }
            }
        }
    }
}
